package db

import (
	"common/config"
	"common/jwts"
	"common/logs"
	"common/utils"
	"errors"
	"github.com/golang-jwt/jwt/v5"
	"gorm.io/gorm"
	"time"
)

const TableNameUser = TablePrefix + "user"

type User struct {
	BaseModel
	Username            string  `gorm:"column:username;type:varchar(20);default:'';comment:手机号 | 账号" json:"username" form:"username"`                                // 手机号 | 账号
	Password            string  `gorm:"column:password;type:varchar(255);default:'';comment:密码" json:"password" form:"password"`                                     // 密码
	TransactionPassword string  `gorm:"column:transaction_password;type:varchar(255);default:'';comment:交易密码" json:"transactionPassword" form:"transactionPassword"` // 交易密码
	Pid                 uint    `gorm:"column:pid;type:int(11);default:0;comment:推荐人id" json:"pid" form:"pid"`                                                       // 推荐人id
	InviteCode          int64   `gorm:"column:invite_code;type:int(6);default:100000;comment:邀请码" json:"invite_code" form:"invite_code"`                             // 邀请码
	RealId              uint    `gorm:"column:real_id;type:int(11);default:0;comment:实名id 0未" json:"real_id" form:"real_id"`                                         // 实名id 0未
	WalletId            uint    `gorm:"column:wallet_id;type:int(11);default:0;comment:钱包id 0未" json:"wallet_id" form:"wallet_id"`                                   // 钱包id 0未
	RoleID              uint    `gorm:"column:role_id;type:int(11);default:0;comment:角色id 0未" json:"role_id" form:"role_id"`                                         // 角色id 0未
	Status              int     `gorm:"column:status;type:tinyint(1);default:1;comment:状态 1正常   -1封禁" json:"status" form:"status"`                                   // 状态 1正常   -1封禁
	Ip                  string  `gorm:"column:ip;type:varchar(15);default:'';comment:登录ip" json:"ip" form:"ip"`                                                      // 登录ip
	Token               string  `gorm:"column:token;type:text" json:"token" form:"token"`                                                                            // 登录token
	EthAddress          *string `gorm:"column:eth_address;type:varchar(200);comment:钱包地址" json:"eth_address" form:"eth_address"`                                     // 钱包地址
	OperationID         *string `gorm:"column:operation_id;type:varchar(200);comment:操作标识" json:"operation_id" form:"operation_id"`                                  // 操作标识
	Money               float64 `gorm:"column:money;type:decimal(10,2);comment:余额" json:"money" form:"money"`                                                        // 余额
	Internal            bool    `gorm:"column:internal;type:tinyint(1);default:0;comment:1:测试账号" json:"internal" form:"internal"`                                    // 1:测试账号
}

func (*User) TableName() string {
	return TableNameUser
}

func (u *User) PwdCheck(password string) error {
	md5String := utils.Md5Password(password)
	//data := []byte(password)
	//md5New := md5.New()
	//md5New.Write(data)
	//// hex转字符串
	//md5String := hex.EncodeToString(md5New.Sum(nil))
	//pwd, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if u.Password == "" {
		u.Password = md5String
	} else {
		if u.Password != md5String {
			return errors.New("账号或密码错误")
		}
	}
	return nil
}

func (u *User) GetPid(client *gorm.DB, inviteCode int64) {
	var pid uint
	client.Model(&u).Where("invite_code=? AND status=?", inviteCode, true).Select("id").Scan(&pid)
	u.Pid = pid
}

func (u *User) IsUsername(client *gorm.DB, username string) bool {
	var count int64
	client.Model(&u).Where("username=?", username).Count(&count)
	return count > 0
}

func (u *User) SaveToken() error {
	//gen token by uid jwt A.B.C A部分头（定义加密算法） B部分 存储数据 C部分 签名
	claims := jwts.CustomClaims{
		Uid: u.ID,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(7 * 24 * time.Hour)),
		},
	}
	var err error
	u.Token, err = jwts.GenToken(&claims, config.Conf.Jwt.Secret)
	if err != nil {
		logs.Error("Register jwt gen token err:%v", err)
		return err
	}
	return nil
}

type UserHasOneRealOfWallet struct {
	User
	Role   Role         `gorm:"foreignKey:ID;references:RoleID" json:"role"`
	Real   UserRealName `gorm:"foreignKey:ID;references:RealId" json:"real"`
	Wallet UserHfWallet `gorm:"foreignKey:ID;references:WalletId" json:"wallet"`
}

type UserHasOneRole struct {
	User
	Role RoleHasOneTransferConfig `gorm:"foreignKey:ID;references:RoleID" json:"role"`
}
